package com.mojie.overscroll.damp

import android.animation.ValueAnimator
import android.graphics.Canvas
import android.util.Log
import android.view.animation.DecelerateInterpolator
import android.widget.EdgeEffect
import androidx.recyclerview.widget.RecyclerView

/**
 *
 * @Author:         lxp
 * @CreateDate:     2024/8/8
 */
class RecyclerViewDampEdgeEffect :RecyclerView.EdgeEffectFactory() {

    companion object{
        private const val TAG = "RecyclerViewEdgeEffect"
        private const val MAX_DISTANCE = 300
    }

    override fun createEdgeEffect(recyclerView: RecyclerView, direction: Int): EdgeEffect {
        return object :EdgeEffect(recyclerView.context){
            override fun onPull(deltaDistance: Float) {
                super.onPull(deltaDistance)
                handlePull(deltaDistance)
            }

            /**
             * 滑动
             */
            override fun onPull(deltaDistance: Float, displacement: Float) {
                super.onPull(deltaDistance, displacement)
                handlePull(deltaDistance)
            }

            private fun handlePull(deltaDistance: Float) {
                val sign = if (direction == DIRECTION_BOTTOM) -1 else 1
                val translationYDelta =
                    sign * MAX_DISTANCE * deltaDistance
                recyclerView.translationY+= translationYDelta
            }

            /**
             * 松手
             */
            override fun onRelease() {
                super.onRelease()
                Log.d(TAG, "onRelease")
                val animator = ValueAnimator.ofFloat(recyclerView.translationY, 0f).setDuration(500)
                animator.interpolator = DecelerateInterpolator(2.0f)
                animator.addUpdateListener { valueAnimator ->
                    recyclerView.translationY = valueAnimator.animatedValue as Float
                }
                animator.start()
            }

            /**
             * 碰撞
             */
            override fun onAbsorb(velocity: Int) {
                super.onAbsorb(velocity)
            }

            override fun draw(canvas: Canvas?): Boolean {
                // 设置大小之后，就不会有绘画阴影效果
                setSize(0, 0)
                return super.draw(canvas)
            }
        }
    }
}